# 获取用户频道视图函数
from flask import g, request
from flask_restful import Resource
from sqlalchemy.orm import load_only
from models.article import Channel, UserChannel
from utils.decorators import login_required
from app import db


class UserChannelResource(Resource):
    """用户频道"""
    # 修改用户频道需要用户登录,设置类装饰器进行权限控制
    method_decorators = {'put': [login_required]}

    def get(self):
        # 获取用户信息
        userid = g.userid

        if userid:  # 判断用户已登录, 查询用户频道

            # 查询用户的频道
            # 使用JOIN连接查询提高关联查询效率
            # 根据用户id查询 并且 根据序号排序
            channels = Channel.query.options(load_only(Channel.id, Channel.name)).join(UserChannel,
                                                                                       Channel.id == UserChannel.channel_id).filter(
                UserChannel.user_id == userid, UserChannel.is_deleted == False).order_by(UserChannel.sequence).all()

            if len(channels) == 0:  # 用户没有选择频道, 查询默认频道
                channels = Channel.query.options(load_only(Channel.id, Channel.name)).filter(
                    Channel.is_default == True).all()

        else:  # 用户未登录, 查询默认频道
            channels = Channel.query.options(load_only(Channel.id, Channel.name)).filter(
                Channel.is_default == True).all()

        # 序列化
        channel_list = [channel.to_dict() for channel in channels]

        # 手动添加"推荐频道"  数据库中没有保存该频道的数据,由推荐系统来返回
        channel_list.insert(0, {'id': 0, 'name': '推荐'})

        # 返回数据
        return {'channels': channel_list}

    def put(self):
        """修改用户频道 重置式更新

        重置式更新 要求先将 当前用户关注的频道进行逻辑删除
        """

        # 获取参数
        userid = g.userid
        # request.json 直接就转成了python形式
        channels = request.json.get('channels')

        # 将原有的该用户频道列表逻辑删除
        UserChannel.query.filter(UserChannel.user_id == userid, UserChannel.is_deleted == False).update(
            {'is_deleted': True})

        # 遍历新的频道列表
        for channel in channels:    # channel:  {"id": 1, "seq": 2}
            # 查询频道数据
            user_channel = UserChannel.query.options(load_only(UserChannel.id)). \
                filter(UserChannel.user_id == userid, UserChannel.channel_id == channel['id']).first()

            if user_channel:
                # 如果频道在用户频道表中, 修改记录(序号,逻辑删除)  sequence  is_deleted
                user_channel.sequence = channel['seq']
                user_channel.is_deleted = False

            else:
                # 如果频道没有在用户频道表中, 添加记录  user_id  channel_id  sequence
                user_channel = UserChannel(user_id=userid, channel_id=channel['id'], sequence=channel['seq'])
                db.session.add(user_channel)

        # 提交事务
        db.session.commit()

        # 返回数据
        return {'channels': channels}
